
//
//  ByUISceneAttributeMakeView.m
//  laserdevice_ios
//
//  Created by pro on 16/12/5.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByUISceneAttributeMakeView.h"

#import "ByBigImageViewController.h"

@interface ByUISceneAttributeMakeView () <UITextFieldDelegate>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) NSMutableArray *attributes;

@property (nonatomic, strong) UIButton *pictureSelectView;

@property (nonatomic, strong) UIControl *showBigImageView;
// data
@property (nonatomic, strong) ByIconChooseDataSource *iconDataSource;

@end

@implementation ByUISceneAttributeMakeView
{
    ByShapeMode _mode;
    
    UIImage *_picture;     // 图片
    
    CGRect _originFrmae;
    
    BOOL canClose;
}
- (instancetype)init {
    
    if (self = [super init]) {
        canClose = YES;
        self.positionMode = ZKBombPositionModeCenter;
        self.popMode = ZKBombPopModeBottom;
    }
    return self;
}




- (UIView *)bgView {
    
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.7, SCREEN_HEIGHT * 0.7)];
        _bgView.backgroundColor = CJ_THEME_COLOR;
        self.contentView = _bgView;
    }
    return _bgView;
}


- (void)showWithShapeModel:(ByShapeModel *)model {
    
    [self.bgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = self.bgView.width;
    CGFloat height = 40;
    // 图形名称
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    nameLabel.adjustsFontSizeToFitWidth = YES;
    nameLabel.font = FONT(16);
    nameLabel.text = model.name;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.bgView addSubview:nameLabel];
    
    // 属性基底
    UIView *attributesView = [[UIView alloc] initWithFrame:CGRectMake(10, nameLabel.bottom, self.bgView.width - 20, 0)];
    attributesView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self.bgView addSubview:attributesView];
    attributesView.tag = 10;
    
    _picture = model.picture;   // 设置图片
    NSArray *titles;
    self.attributes = [model.attributes mutableCopy];
    [self.attributes insertObject:model.name atIndex:0];
    _mode = model.mode;
    switch (model.mode) {
        case ByShapeModeLine:
        {
            titles = @[STRING(@"mingcheng"), STRING(@"chang"), STRING(@"tupian")];
            break;
        }
        case ByShapeModeAngle:
        {
            titles = @[STRING(@"mingcheng"), STRING(@"jiaodu"), STRING(@"changdu1"), STRING(@"changdu2"), STRING(@"tupian")];
            break;
        }
        case ByShapeModeTriangle:
        {
            titles = @[STRING(@"mingcheng"), STRING(@"bianchang1"), STRING(@"bianchang2"), STRING(@"bianchang3"), STRING(@"mianji"), STRING(@"tupian")];
            break;
        }
        case ByShapeModeSquare:
        {
            titles = @[STRING(@"mingcheng"), STRING(@"chang"), STRING(@"kuan"), STRING(@"mianji"), STRING(@"tupian")];
            break;
        }
        case ByShapeModeTrapezoid:
        {
            titles = @[STRING(@"mingcheng"), STRING(@"shangdi"), STRING(@"xiadi"), STRING(@"gao"), STRING(@"mianji"), STRING(@"tupian")];
            break;
        }
        case ByShapeModeCuboids:
        {
            titles = @[STRING(@"mingcheng"), STRING(@"chang"), STRING(@"kuan"), STRING(@"gao"), STRING(@"tiji"), STRING(@"tupian")];
            break;
        }
        default:
            break;
    }
    // 根据model来创建属性视图
    [self createAttributeViewsToView:attributesView attributeTitles:titles attributes:self.attributes];
    
    attributesView.height = attributesView.subviews.lastObject.bottom + 10;
    
    // 确定和取消
    x = 0;
    y = attributesView.bottom + 10;
    width = self.bgView.width / 2;
    height = 30;
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(x, y, width, height);
    cancleBtn.titleLabel.font = FONT(15);
    [cancleBtn setTitle:STRING(@"quxiao") forState:UIControlStateNormal];
    [cancleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:cancleBtn];
    
    x = cancleBtn.right;
    y = cancleBtn.top;
    width = cancleBtn.width;
    height = cancleBtn.height;
    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    okBtn.frame = CGRectMake(x, y, width, height);
    okBtn.titleLabel.font = FONT(15);
    [okBtn setTitle:STRING(@"queding") forState:UIControlStateNormal];
    [okBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [okBtn addTarget:self action:@selector(ok) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:okBtn];
    
    
    self.bgView.height = okBtn.bottom + 10;

    
    [self show];
}


// 创建水平排版的视图（可点击）
- (void)createAttributeViewsToView:(UIView *)basalView
                          attributeTitles:(NSArray *)attributeTitles
                               attributes:(NSArray *)attributes {
    
    __block CGFloat x, y, width, height;
    
    [attributeTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        width = 50;
        height = 30;
        x = 10;
        y = 10 + (10 + height) * idx;
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        titleLabel.adjustsFontSizeToFitWidth = YES;
        titleLabel.font = FONT(14);
        titleLabel.text = [NSString stringWithFormat:@"%@:", obj];
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [basalView addSubview:titleLabel];
        
        // 非最后一个
        if (idx != attributeTitles.count - 1) {
            x = titleLabel.right;
            y = titleLabel.top;
            width = basalView.width - 10 - x;
            height = titleLabel.height;
            UITextField *contentTf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
            contentTf.backgroundColor = [UIColor whiteColor];
            contentTf.textColor = [UIColor blackColor];
            contentTf.font = FONT(14);
            contentTf.textAlignment = NSTextAlignmentCenter;
            contentTf.text = attributes[idx];
            contentTf.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
            contentTf.layer.borderWidth = 1;
            [basalView addSubview:contentTf];
            contentTf.delegate = self;
            contentTf.tag = 100 + idx;
            
            // 单位
            x = 0;
            y = 0;
            width = 30;
            height = 15;
            UILabel *unitLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
            unitLabel.adjustsFontSizeToFitWidth = YES;
            unitLabel.font = FONT(14);
            int unit = [ByCommonCache getSystemUnit].intValue;
            switch (unit) {
                case 0: // 米
                    unitLabel.text = @"m";
                    if ([obj isEqualToString:STRING(@"tiji")]) {
                        unitLabel.text = @"m³";
                    }
                    if ([obj isEqualToString:STRING(@"mianji")]) {
                        unitLabel.text = @"m²";
                    }
                    break;
                case 1: // 英尺
                    unitLabel.text = @"ft";
                    if ([obj isEqualToString:STRING(@"tiji")]) {
                        unitLabel.text = @"ft³";
                    }
                    if ([obj isEqualToString:STRING(@"mianji")]) {
                        unitLabel.text = @"ft²";
                    }
                    break;
                case 2: // 英寸
                    unitLabel.text = @"in";
                    if ([obj isEqualToString:STRING(@"tiji")]) {
                        unitLabel.text = @"in³";
                    }
                    if ([obj isEqualToString:STRING(@"mianji")]) {
                        unitLabel.text = @"in²";
                    }
                    break;
                case 3: // 英尺+英寸
                    unitLabel.text = @"ft";
                    if ([obj isEqualToString:STRING(@"tiji")]) {
                        unitLabel.text = @"ft³";
                    }
                    if ([obj isEqualToString:STRING(@"mianji")]) {
                        unitLabel.text = @"ft²";
                    }
                    break;
                default:
                    break;
            }
            if ([obj isEqualToString:STRING(@"jiaodu")]) {
                unitLabel.text = @"°";
            }

            unitLabel.textColor = [UIColor blackColor];
            unitLabel.textAlignment = NSTextAlignmentCenter;
            unitLabel.width = [unitLabel.text getSizeOfString:14].width + 5;
            
            if (idx != 0) {
                contentTf.rightViewMode = UITextFieldViewModeAlways;
                contentTf.rightView = unitLabel;
            }


        } else {
            x = titleLabel.right;
            y = titleLabel.top;
            width = 80;
            height = 80;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(x, y, width, height);
            [button setImage:[UIImage imageNamed:@"scene_modelPhoto"] forState:UIControlStateNormal];
            [basalView addSubview:button];
            
            if (_picture) {
                [button setImage:_picture forState:UIControlStateNormal];
            }
            
            [button addTarget:self action:@selector(getPicture) forControlEvents:UIControlEventTouchUpInside];
            
            _pictureSelectView = button;
        }
        
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    NSInteger index = textField.tag - 100;
    
    [self.attributes replaceObjectAtIndex:index withObject:textField.text];
    
    // 要自动算面积或体积
    switch (_mode) {
        case ByShapeModeLine:
        {
            break;
        }
        case ByShapeModeAngle:
        {
            break;
        }
        case ByShapeModeTriangle:
        {
            if (index == 1 || index == 2 || index == 3) {
                CGFloat l1 = [self.attributes[1] floatValue];
                CGFloat l2 = [self.attributes[2] floatValue];
                CGFloat l3 = [self.attributes[3] floatValue];
                if (l1 != 0 && l2 != 0 && l3 != 0) {
                    CGFloat c = (l1 + l2 + l3) / 2;
                    CGFloat s = sqrt((c * (c - l1) * (c - l2) * (c - l3)));
                    
                    if (isnan(s) || s == 0) {
                        canClose = NO;
                        [UIAlertView showWithTitle:nil message:STRING(@"bianchangshezhibuzhengque") cancelButtonTitle:STRING(@"queding") otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                            UIView *basalView = [self.bgView viewWithTag:10];
                            for (int i = 1; i <= 3; i ++) {
                                UITextField *tf = [basalView viewWithTag:100 + i];
                                NSString *text = [NSString stringWithFormat:@"L%i", i];
                                tf.text = text;
                                [self.attributes replaceObjectAtIndex:i withObject:text];
                                canClose = YES;
                            }
                        }];
                        return;
                    }
                    [self.attributes replaceObjectAtIndex:4 withObject:[NSString stringWithFormat:@"%.3lf", s]];
                    UITextField *tf = [[textField superview] viewWithTag:104];
                    tf.text = self.attributes[4];
                }
            }
            break;
        }
        case ByShapeModeSquare:
        {
            if (index == 1 || index == 2) {
                CGFloat l = [self.attributes[1] floatValue];
                CGFloat w = [self.attributes[2] floatValue];
                if (l != 0 && w != 0) {
                    CGFloat s = l * w;
                    [self.attributes replaceObjectAtIndex:3 withObject:[NSString stringWithFormat:@"%.3lf", s]];
                    UITextField *tf = [[textField superview] viewWithTag:103];
                    tf.text = self.attributes[3];
                }
            }
            break;
        }
        case ByShapeModeTrapezoid:
        {
            if (index == 1 || index == 2 || index == 3) {
                CGFloat l_u = [self.attributes[1] floatValue];
                CGFloat l_d = [self.attributes[2] floatValue];
                CGFloat h = [self.attributes[3] floatValue];
                if (l_u != 0 && l_d != 0 && h != 0) {
                    CGFloat s = (l_u + l_d) * h / 2;
                    [self.attributes replaceObjectAtIndex:4 withObject:[NSString stringWithFormat:@"%.3lf", s]];
                    UITextField *tf = [[textField superview] viewWithTag:104];
                    tf.text = self.attributes[4];
                }
            }
            break;
        }
        case ByShapeModeCuboids:
        {
            if (index == 1 || index == 2 || index == 3) {
                CGFloat l = [self.attributes[1] floatValue];
                CGFloat w = [self.attributes[2] floatValue];
                CGFloat h = [self.attributes[3] floatValue];
                if (l != 0 && w != 0 && h != 0) {
                    CGFloat v = l * w * h;
                    [self.attributes replaceObjectAtIndex:4 withObject:[NSString stringWithFormat:@"%.3lf", v]];
                    UITextField *tf = [[textField superview] viewWithTag:104];
                    tf.text = self.attributes[4];
                }
            }
            break;
        }
        default:
            break;
    }

}


#pragma mark - 点击时间
- (void)cancle {
    
    [self remove];
}
- (void)ok {
    
    UIView *attributesView = [self.bgView viewWithTag:10];
    for (UIView *subview in attributesView.subviews) {
        if ([subview isKindOfClass:[UITextField class]]) {
            [((UITextField *)subview) resignFirstResponder];
        }
    }
    
    if (self.backAction) {
        self.backAction(self.attributes[0], [self.attributes subarrayWithRange:NSMakeRange(1, self.attributes.count - 1)], _picture);
    }
    
    [self remove];
}
- (void)remove {
    
    UIView *attributesView = [self.bgView viewWithTag:10];
    for (UIView *subview in attributesView.subviews) {
        if ([subview isKindOfClass:[UITextField class]]) {
            [((UITextField *)subview) resignFirstResponder];
        }
    }
    
    if (canClose) {
        [super remove];
    }
}

- (void)getPicture {
    
    if (self.selectPictureBlock) {
        self.selectPictureBlock();
    }
    
    __weak typeof(self) weakself = self;
    
    if (!_picture) {        // 去选图片
        _iconDataSource = [[ByIconChooseDataSource alloc] init];
        [_iconDataSource fireWithViewController:[ByBaseVC topByViewController]];
        __weak typeof(_pictureSelectView) weakBtn = _pictureSelectView;
        _iconDataSource.completeBlock = ^ (UIImage *image) {
            _picture = image;
            [weakBtn setImage:image forState:UIControlStateNormal];
        };
        [self.iconDataSource makeConfigToSelectIcon];
    } else {
        NSLog(@"已经有图片了");
        _iconDataSource = [[ByIconChooseDataSource alloc] initWithCustom:@[@"查看图片"]];
        [_iconDataSource fireWithViewController:[ByBaseVC topByViewController]];
        __weak typeof(_pictureSelectView) weakBtn = _pictureSelectView;
        _iconDataSource.completeBlock = ^ (UIImage *image) {
            _picture = image;
            [weakBtn setImage:image forState:UIControlStateNormal];
        };
        _iconDataSource.completeBlockV2 = ^ (NSInteger otherIndex) {
            
            if (otherIndex == 0) {
                [weakself performSelector:@selector(lookBigImage) withObject:nil afterDelay:0.5];
            }
        };
        [self.iconDataSource makeConfigToSelectIcon];
        

    }
}

- (void)lookBigImage {
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    self.showBigImageView = [[UIControl alloc] initWithFrame:keyWindow.bounds];
    self.showBigImageView.backgroundColor = [UIColor blackColor];
    [self.showBigImageView addTarget:self action:@selector(removeBigImageView) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *copyView = [[UIImageView alloc] init];
    copyView.image = _picture;
    //        UIView *copyView = [_pictureSelectView snapshotViewAfterScreenUpdates:NO];
    copyView.userInteractionEnabled = NO;
    [self.showBigImageView addSubview:copyView];
    copyView.tag = 100;
    
    UIView *basalView = [self.bgView viewWithTag:10];
    CGRect frame = [basalView convertRect:_pictureSelectView.frame toView:keyWindow];
    _originFrmae = frame;
    [keyWindow addSubview:self.showBigImageView];
    [keyWindow bringSubviewToFront:self.showBigImageView];
    copyView.frame = _originFrmae;
    
    CGFloat x, y, width, height;
    width = keyWindow.width;
    height = width;
    x = 0;
    y = (keyWindow.height - height) / 2;
    CGRect endFrame = CGRectMake(x, y, width, height);
    [UIView animateWithDuration:0.5 animations:^{
        
        copyView.frame = endFrame;
    }];
    

}

- (void)removeBigImageView {
    
    
    UIView *copyView = [self.showBigImageView viewWithTag:100];
    [UIView animateWithDuration:0.5 animations:^{
        
        copyView.frame = _originFrmae;
    } completion:^(BOOL finished) {
        [self.showBigImageView removeFromSuperview];
    }];
}

@end
